import React, { useEffect, useRef, useState, useCallback } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import { CITY_DATA } from '../data';
import type { CityData } from '../data';
import "./StoreMapPage.css"

declare namespace AMap {
  class Size {
    constructor(width: number, height: number);
    getWidth(): number;
    getHeight(): number;
  }

  class Pixel {
    constructor(x: number, y: number);
    getX(): number;
    getY(): number;
  }

  class Icon {
    constructor(options: {
      size: Size;
      image: string;
      imageSize: Size;
    });
    setImageSize(size: Size): void;
  }

  class Bounds {
    constructor(southWest: [number, number], northEast: [number, number]);
  }

  interface Label {
    content: string;
    direction: 'top' | 'right' | 'bottom' | 'left' | 'center';
  }

  interface MarkerOptions {
    position: [number, number];
    title?: string;
    icon?: Icon;
    offset?: Pixel;
    animation?: string;
    content?: HTMLElement | string;
    label?: Label;
  }

  interface InfoWindowOptions {
    isCustom?: boolean;
    autoMove?: boolean;
    offset?: Pixel;
    content?: string;
  }

  interface DistrictLayerOptions {
    zIndex: number;
    adcode: string[];
    depth: number;
    styles: {
      fill: string;
      'province-stroke': string;
      'city-stroke': string;
      'fill-opacity': number;
      'province-stroke-width': number;
      'city-stroke-width': number;
      'coastline-stroke': string;
      'coastline-stroke-width': number;
      'nationalmedical-stroke': string;
      'nationalmedical-stroke-width': number;
    };
  }

  interface DistrictLayer {
    Province: {
      new (options: DistrictLayerOptions): {
        setMap: (map: any) => void;
      };
    };
  }

  interface Map {
    add(markers: any | any[]): void;
    remove(markers: any | any[]): void;
    setZoomAndCenter(zoom: number, center: [number, number], immediately?: boolean): void;
    setLimitBounds(bounds: Bounds): void;
    setBounds(bounds: Bounds, options?: { padding?: [number, number, number, number] }): void;
    destroy(): void;
  }

  interface Marker {
    on(event: string, handler: () => void): void;
    getPosition(): { getLng(): number; getLat(): number };
    getContentDom(): HTMLElement;
  }

  interface InfoWindow {
    setContent(content: string): void;
    open(map: Map, position: [number, number] | { getLng(): number; getLat(): number }): void;
    close(): void;
  }
}

// 地图配置常量
const MAP_CONFIG = {
  KEY: 'ce092740b1e7efd4adc87289d58cfd46',
  VERSION: '2.0',
  PLUGINS: ['AMap.DistrictLayer', 'AMap.Scale', 'AMap.ToolBar', 'AMap.DistrictSearch'] as string[],
  INITIAL_VIEW: {
    ZOOM: 5,
    CENTER: [104.5, 38.5] as [number, number],
    STYLE: 'amap://styles/light',
    VIEW_MODE: '2D' as const,
    FEATURES: ['bg', 'building', 'point'] as string[],
    PITCH: 0
  },
  BOUNDS: {
    SW: [70, 15] as [number, number],  // 西南角经纬度
    NE: [140, 55] as [number, number]  // 东北角经纬度
  }
} as const;

// 样式配置常量
const STYLE_CONFIG = {
  MARKER: {
    SIZE: {
      WIDTH: 48,
      HEIGHT: 48
    },
    COLORS: {
      PRIMARY: '#1890ff',
      PRIMARY_ALPHA: 'rgba(24, 144, 255, 0.9)',
      PRIMARY_ALPHA_HOVER: 'rgba(24, 144, 255, 1)',
      WHITE: '#ffffff',
      TEXT_PRIMARY: '#262626',
      TEXT_SECONDARY: 'rgba(0, 0, 0, 0.65)',
      TEXT_TERTIARY: 'rgba(0, 0, 0, 0.45)',
      BORDER: 'rgba(24, 144, 255, 0.3)'
    },
    SHADOW: {
      DEFAULT: '0 4px 12px rgba(24, 144, 255, 0.35)',
      HOVER: '0 4px 12px rgba(24, 144, 255, 0.45)'
    }
  },
  PROVINCE_LAYER: {
    STROKE: '#d1d1d1',
    FILL: '#ffffff',
    FILL_OPACITY: 0.05,
    STROKE_WIDTH: 1
  }
} as const;

// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: MAP_CONFIG.KEY
};

// 更新全局声明
declare global {
  interface Window {
    _AMapSecurityConfig: {
      securityJsCode: string;
    };
    closeInfoWindow: () => void;
    _showStoreLocation: (lng: number, lat: number, storeName: string, cityLng?: number, cityLat?: number) => void;
    AMap: {
      Map: new (container: string | HTMLElement, options: MapOptions) => AMap.Map;
      Marker: new (options: AMap.MarkerOptions) => AMap.Marker;
      InfoWindow: new (options: AMap.InfoWindowOptions) => AMap.InfoWindow;
      Pixel: new (x: number, y: number) => AMap.Pixel;
      Size: new (width: number, height: number) => AMap.Size;
      Icon: new (options: { size: AMap.Size; image: string; imageSize: AMap.Size }) => AMap.Icon;
      Bounds: new (southWest: [number, number], northEast: [number, number]) => AMap.Bounds;
      DistrictLayer: AMap.DistrictLayer;
    };
  }
}

interface BoundaryStyle {
  strokeColor: string;
  strokeWeight: number;
  strokeOpacity: number;
  fillColor: string;
  fillOpacity: number;
}

interface BoundaryStyles {
  country: BoundaryStyle;
  province: BoundaryStyle;
  city: BoundaryStyle;
  district: BoundaryStyle;
}

// 边界线样式配置
const BOUNDARY_STYLES: BoundaryStyles = {
  country: {
    strokeColor: STYLE_CONFIG.MARKER.COLORS.PRIMARY,
    strokeWeight: 3,
    strokeOpacity: 1,
    fillColor: STYLE_CONFIG.MARKER.COLORS.WHITE,
    fillOpacity: 0
  },
  province: {
    strokeColor: '#40a9ff',
    strokeWeight: 2,
    strokeOpacity: 0.8,
    fillColor: STYLE_CONFIG.MARKER.COLORS.WHITE,
    fillOpacity: 0
  },
  city: {
    strokeColor: '#69c0ff',
    strokeWeight: 1.5,
    strokeOpacity: 0.6,
    fillColor: STYLE_CONFIG.MARKER.COLORS.WHITE,
    fillOpacity: 0
  },
  district: {
    strokeColor: '#91d5ff',
    strokeWeight: 1,
    strokeOpacity: 0.4,
    fillColor: STYLE_CONFIG.MARKER.COLORS.WHITE,
    fillOpacity: 0
  }
} as const;

interface MapOptions {
  zoom: number;
  center: [number, number];
  mapStyle: string;
  viewMode: '2D' | '3D';
  features: string[];
  pitch: number;
}

const StoreMapPage: React.FC = () => {
  const mapContainer = useRef<HTMLDivElement>(null);
  const mapInstance = useRef<AMap.Map | null>(null);
  const markersRef = useRef<AMap.Marker[]>([]);
  const storeMarkerRef = useRef<AMap.Marker | null>(null);
  const infoWindowRef = useRef<AMap.InfoWindow | null>(null);
  const hoverInfoWindowRef = useRef<AMap.InfoWindow | null>(null);
  const observerRef = useRef<MutationObserver | null>(null);
  const [mapReady, setMapReady] = useState(false);

  // 优化地图中的所有 Canvas 元素
  const optimizeMapCanvases = useCallback(() => {
    if (!mapContainer.current) return;
    
    const canvases = mapContainer.current.getElementsByTagName('canvas');
    Array.from(canvases).forEach(canvas => {
      const ctx = canvas.getContext('2d', { willReadFrequently: true });
      if (ctx) {
        // 重新创建上下文以应用优化
        canvas.width = canvas.width;
      }
    });
  }, []);

  // 监听 DOM 变化以优化新添加的 Canvas 元素
  useEffect(() => {
    if (!mapContainer.current) return;

    observerRef.current = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        mutation.addedNodes.forEach((node) => {
          if (node instanceof HTMLElement) {
            const canvases = node.getElementsByTagName('canvas');
            if (canvases.length > 0 || node instanceof HTMLCanvasElement) {
              optimizeMapCanvases();
            }
          }
        });
      });
    });

    observerRef.current.observe(mapContainer.current, {
      childList: true,
      subtree: true
    });

    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, [optimizeMapCanvases]);

  // 创建信息窗口内容
  const createInfoWindowContent = useCallback((city: CityData) => {
    const storesList = city.stores.map(store => `
      <div style="
        border-bottom: 1px solid rgba(0, 0, 0, 0.06);
        padding: 12px;
        margin-bottom: 4px;
        background: rgba(255, 255, 255, 0.95);
        border-radius: 4px;
        transition: all 0.3s;
        cursor: pointer;
      "
      onclick="window._showStoreLocation(${store.location[0]}, ${store.location[1]}, '${store.name.replace(/'/g, "\\'")}', ${city.position[0]}, ${city.position[1]});"
      onmouseover="this.style.background='#fff'; this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 12px rgba(0,0,0,0.08)'"
      onmouseout="this.style.background='rgba(255, 255, 255, 0.95)'; this.style.transform='translateY(0)'; this.style.boxShadow='none'"
      >
        <div style="
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
        ">
          <div style="
            font-weight: bold;
            color: #262626;
            font-size: 16px;
          ">${store.name}</div>
          <div style="
            font-size: 13px;
            color: ${STYLE_CONFIG.MARKER.COLORS.PRIMARY};
            padding: 6px 16px;
            border: 1px solid ${STYLE_CONFIG.MARKER.COLORS.PRIMARY};
            border-radius: 20px;
            background: transparent;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 4px;
          "
          onmouseover="this.style.background='${STYLE_CONFIG.MARKER.COLORS.PRIMARY}'; this.style.color='#fff'"
          onmouseout="this.style.background='transparent'; this.style.color='${STYLE_CONFIG.MARKER.COLORS.PRIMARY}'"
          >
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" style="margin-top: -2px;">
              <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zM7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 2.88-2.88 7.19-5 9.88C9.92 16.21 7 11.85 7 9z"/>
              <circle cx="12" cy="9" r="2.5"/>
            </svg>
            查看位置
          </div>
        </div>
        <div style="
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;
        ">
          <div style="
            font-size: 13px;
            color: ${STYLE_CONFIG.MARKER.COLORS.TEXT_SECONDARY};
            display: flex;
            align-items: center;
            gap: 4px;
          ">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
              <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
            </svg>
            ${store.address}
          </div>
          <div style="
            font-size: 13px;
            color: ${STYLE_CONFIG.MARKER.COLORS.TEXT_TERTIARY};
            padding: 2px 8px;
            border-radius: 12px;
            background: rgba(0, 0, 0, 0.04);
          ">${store.type}</div>
        </div>
        <div style="
          display: flex;
          align-items: center;
          gap: 4px;
        ">
          <svg viewBox="0 0 24 24" width="16" height="16" fill="${STYLE_CONFIG.MARKER.COLORS.PRIMARY}">
            <path d="M11.8 10.9c-2.27-.59-3-1.2-3-2.15 0-1.09 1.01-1.85 2.7-1.85 1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-1.94.42-3.5 1.68-3.5 3.61 0 2.31 1.91 3.46 4.7 4.13 2.5.6 3 1.48 3 2.41 0 .69-.49 1.79-2.7 1.79-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c1.95-.37 3.5-1.5 3.5-3.55 0-2.84-2.43-3.81-4.7-4.4z"/>
          </svg>
          <span style="
            color: ${STYLE_CONFIG.MARKER.COLORS.PRIMARY};
            font-weight: bold;
            font-size: 16px;
          ">¥${store.sales.toLocaleString()}</span>
        </div>
      </div>
    `).join('');

    return `
      <div style="
        padding: 20px;
        min-width: 360px;
        max-width: 480px;
        max-height: 600px;
        overflow-y: auto;
        position: relative;
        background: rgba(255, 255, 255, 0.98);
        box-shadow: 0 8px 24px rgba(0,0,0,0.12);
        border: 1px solid rgba(24, 144, 255, 0.15);
        border-radius: 8px;
        color: #262626;
        backdrop-filter: blur(10px);
      ">
        <div style="
          position: absolute;
          top: 12px;
          right: 12px;
          width: 28px;
          height: 28px;
          background: rgba(0, 0, 0, 0.04);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          font-size: 18px;
          color: rgba(0, 0, 0, 0.45);
          z-index: 1;
          transition: all 0.3s;
        " class="close-button" 
          onclick="closeInfoWindow();"
          onmouseover="this.style.background='rgba(0, 0, 0, 0.08)'; this.style.transform='rotate(90deg)'"
          onmouseout="this.style.background='rgba(0, 0, 0, 0.04)'; this.style.transform='rotate(0)'"
        >
          ×
        </div>
        <div style="
          margin-bottom: 24px;
        ">
          <div style="
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 12px;
            padding-right: 32px;
            color: #262626;
            display: flex;
            align-items: center;
            gap: 8px;
          ">
            <svg viewBox="0 0 24 24" width="24" height="24" fill="${STYLE_CONFIG.MARKER.COLORS.PRIMARY}">
              <path d="M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z"/>
            </svg>
            ${city.name}门店销售情况
          </div>
          <div style="
            font-size: 16px;
            color: ${STYLE_CONFIG.MARKER.COLORS.PRIMARY};
            display: flex;
            align-items: center;
            gap: 6px;
          ">
            <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
              <path d="M11.8 10.9c-2.27-.59-3-1.2-3-2.15 0-1.09 1.01-1.85 2.7-1.85 1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-1.94.42-3.5 1.68-3.5 3.61 0 2.31 1.91 3.46 4.7 4.13 2.5.6 3 1.48 3 2.41 0 .69-.49 1.79-2.7 1.79-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c1.95-.37 3.5-1.5 3.5-3.55 0-2.84-2.43-3.81-4.7-4.4z"/>
            </svg>
            总销售额：¥${city.value.toLocaleString()}
          </div>
        </div>
        <div style="
          display: grid;
          gap: 8px;
        ">
          ${storesList}
        </div>
      </div>
    `;
  }, []);

  // 显示门店位置
  const showStoreLocation = useCallback((lng: number, lat: number, storeName: string, cityLng?: number, cityLat?: number) => {
    const map = mapInstance.current;
    if (!map || !mapReady) return;

    // 移除之前的门店标记
    if (storeMarkerRef.current) {
      map.remove(storeMarkerRef.current);
      storeMarkerRef.current = null;
    }

    // 创建新的门店标记
    const marker = new window.AMap.Marker({
      position: [lng, lat],
      title: storeName,
      icon: new window.AMap.Icon({
        size: new window.AMap.Size(48, 48),
        image: '',
        imageSize: new window.AMap.Size(48, 48)
      }),
      offset: new window.AMap.Pixel(-24, -48),
      animation: 'AMAP_ANIMATION_DROP'
    } as AMap.MarkerOptions);

    // 创建详细信息窗口
    const detailWindow = new window.AMap.InfoWindow({
      isCustom: true,
      autoMove: true,
      offset: new window.AMap.Pixel(0, -20),
      content: `
        <div style="
          padding: 16px;
          min-width: 280px;
          background: rgba(255, 255, 255, 0.98);
          border-radius: 8px;
          box-shadow: 0 2px 12px rgba(0,0,0,0.1);
          border: 1px solid ${STYLE_CONFIG.MARKER.COLORS.BORDER};
          font-size: 14px;
          color: ${STYLE_CONFIG.MARKER.COLORS.TEXT_PRIMARY};
          backdrop-filter: blur(8px);
        ">
          <div style="
            font-size: 16px;
            font-weight: bold;
            color: ${STYLE_CONFIG.MARKER.COLORS.PRIMARY};
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
          ">
            <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
              <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
            </svg>
            ${storeName}
          </div>
          <div style="
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
            color: ${STYLE_CONFIG.MARKER.COLORS.TEXT_SECONDARY};
          ">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
              <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 2c2.76 0 5 2.24 5 5 0 2.88-2.88 7.19-5 9.88C9.92 16.21 7 11.85 7 9c0-2.76 2.24-5 5-5z"/>
              <circle cx="12" cy="9" r="2.5"/>
            </svg>
            经度：${lng.toFixed(6)}
          </div>
          <div style="
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 12px;
            color: ${STYLE_CONFIG.MARKER.COLORS.TEXT_SECONDARY};
          ">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
              <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 2c2.76 0 5 2.24 5 5 0 2.88-2.88 7.19-5 9.88C9.92 16.21 7 11.85 7 9c0-2.76 2.24-5 5-5z"/>
              <circle cx="12" cy="9" r="2.5"/>
            </svg>
            纬度：${lat.toFixed(6)}
          </div>
          <div style="
            display: flex;
            gap: 8px;
          ">
            <button onclick="window.open('https://uri.amap.com/marker?position=${lng},${lat}&name=${encodeURIComponent(storeName)}&src=myapp&coordinate=gaode&callnative=0', '_blank')" style="
              flex: 1;
              padding: 8px 16px;
              border: 1px solid ${STYLE_CONFIG.MARKER.COLORS.PRIMARY};
              border-radius: 20px;
              background: transparent;
              color: ${STYLE_CONFIG.MARKER.COLORS.PRIMARY};
              font-size: 13px;
              cursor: pointer;
              transition: all 0.3s;
              display: flex;
              align-items: center;
              justify-content: center;
              gap: 4px;
            "
            onmouseover="this.style.background='${STYLE_CONFIG.MARKER.COLORS.PRIMARY}'; this.style.color='#fff'"
            onmouseout="this.style.background='transparent'; this.style.color='${STYLE_CONFIG.MARKER.COLORS.PRIMARY}'"
            >
              <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                <path d="M18.92 6.01C18.72 5.42 18.16 5 17.5 5h-11c-.66 0-1.21.42-1.42 1.01L3 12v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.85 7h10.29l1.08 3.11H5.77L6.85 7zM19 17H5v-5h14v5z"/>
                <circle cx="7.5" cy="14.5" r="1.5"/>
                <circle cx="16.5" cy="14.5" r="1.5"/>
              </svg>
              导航到这里
            </button>
            <button onclick="window.open('https://www.amap.com/search?query=${encodeURIComponent(storeName)}&city=110000', '_blank')" style="
              flex: 1;
              padding: 8px 16px;
              border: 1px solid ${STYLE_CONFIG.MARKER.COLORS.PRIMARY};
              border-radius: 20px;
              background: transparent;
              color: ${STYLE_CONFIG.MARKER.COLORS.PRIMARY};
              font-size: 13px;
              cursor: pointer;
              transition: all 0.3s;
              display: flex;
              align-items: center;
              justify-content: center;
              gap: 4px;
            "
            onmouseover="this.style.background='${STYLE_CONFIG.MARKER.COLORS.PRIMARY}'; this.style.color='#fff'"
            onmouseout="this.style.background='transparent'; this.style.color='${STYLE_CONFIG.MARKER.COLORS.PRIMARY}'"
            >
              <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
              </svg>
              周边搜索
            </button>
          </div>
        </div>
      `
    });

    // 点击标记时显示详细信息
    marker.on('click', () => {
      detailWindow.open(map, marker.getPosition());
    });

    // 添加标记到地图
    map.add(marker);
    storeMarkerRef.current = marker;

    // 更新地图视图
    if (cityLng !== undefined && cityLat !== undefined) {
      const bounds = new window.AMap.Bounds(
        [Math.min(lng, cityLng), Math.min(lat, cityLat)],
        [Math.max(lng, cityLng), Math.max(lat, cityLat)]
      );
      map.setBounds(bounds, {
        padding: [50, 50, 50, 50]
      });
    } else {
      map.setZoomAndCenter(15, [lng, lat], true);
    }

    // 自动显示详细信息窗口
    detailWindow.open(map, [lng, lat]);
  }, [mapReady]);

  const cleanupMap = useCallback(() => {
    if (mapInstance.current) {
      // 清理所有标记和图层
      if (storeMarkerRef.current) {
        mapInstance.current.remove(storeMarkerRef.current);
      }
      if (markersRef.current.length) {
        mapInstance.current.remove(markersRef.current);
      }
      if (infoWindowRef.current) {
        infoWindowRef.current.close();
      }
      if (hoverInfoWindowRef.current) {
        hoverInfoWindowRef.current.close();
      }
      // 销毁地图实例
      mapInstance.current.destroy();
      mapInstance.current = null;
    }
    // 清理全局函数和观察器
    window.closeInfoWindow = () => { };
    window._showStoreLocation = () => { };
    if (observerRef.current) {
      observerRef.current.disconnect();
    }
  }, []);

  // 初始化地图
  useEffect(() => {
    let mounted = true;

    const initMap = async () => {
      try {
        await AMapLoader.load({
          key: MAP_CONFIG.KEY,
          version: MAP_CONFIG.VERSION,
          plugins: MAP_CONFIG.PLUGINS
        });

        if (!mounted || !mapContainer.current) return;

        // 创建地图实例
        const map = new window.AMap.Map(mapContainer.current, {
          zoom: MAP_CONFIG.INITIAL_VIEW.ZOOM,
          center: MAP_CONFIG.INITIAL_VIEW.CENTER,
          mapStyle: MAP_CONFIG.INITIAL_VIEW.STYLE,
          viewMode: MAP_CONFIG.INITIAL_VIEW.VIEW_MODE,
          features: MAP_CONFIG.INITIAL_VIEW.FEATURES,
          pitch: MAP_CONFIG.INITIAL_VIEW.PITCH
        });

        mapInstance.current = map;

        // 优化地图中的 Canvas 元素
        optimizeMapCanvases();

        // 创建信息窗体
        const infoWindow = new window.AMap.InfoWindow({
          isCustom: true,
          autoMove: true,
          offset: new window.AMap.Pixel(0, -20)
        });

        const hoverInfoWindow = new window.AMap.InfoWindow({
          isCustom: true,
          autoMove: true,
          offset: new window.AMap.Pixel(0, -20)
        });

        infoWindowRef.current = infoWindow;
        hoverInfoWindowRef.current = hoverInfoWindow;

        // 添加全局函数
        window.closeInfoWindow = () => {
          infoWindow.close();
        };

        window._showStoreLocation = (lng: number, lat: number, storeName: string, cityLng?: number, cityLat?: number) => {
          showStoreLocation(lng, lat, storeName, cityLng, cityLat);
        };

        // 创建省份图层
        const provinceLayer = new window.AMap.DistrictLayer.Province({
          zIndex: 12,
          adcode: [],
          depth: 1,
          styles: {
            'fill': STYLE_CONFIG.PROVINCE_LAYER.FILL,
            'province-stroke': STYLE_CONFIG.PROVINCE_LAYER.STROKE,
            'city-stroke': STYLE_CONFIG.PROVINCE_LAYER.STROKE,
            'fill-opacity': STYLE_CONFIG.PROVINCE_LAYER.FILL_OPACITY,
            'province-stroke-width': STYLE_CONFIG.PROVINCE_LAYER.STROKE_WIDTH,
            'city-stroke-width': STYLE_CONFIG.PROVINCE_LAYER.STROKE_WIDTH,
            'coastline-stroke': STYLE_CONFIG.PROVINCE_LAYER.STROKE,
            'coastline-stroke-width': STYLE_CONFIG.PROVINCE_LAYER.STROKE_WIDTH,
            'nationalmedical-stroke': STYLE_CONFIG.PROVINCE_LAYER.STROKE,
            'nationalmedical-stroke-width': STYLE_CONFIG.PROVINCE_LAYER.STROKE_WIDTH
          }
        });

        // 添加省份图层
        map.add(provinceLayer);

        // 创建城市标记
        const markers = CITY_DATA.map(city => {
          const markerContent = document.createElement('div');
          markerContent.className = 'city-marker';
          markerContent.innerHTML = `
            <div style="
              width: ${STYLE_CONFIG.MARKER.SIZE.WIDTH}px;
              height: ${STYLE_CONFIG.MARKER.SIZE.HEIGHT}px;
              background: ${STYLE_CONFIG.MARKER.COLORS.PRIMARY_ALPHA};
              border: 2px solid ${STYLE_CONFIG.MARKER.COLORS.WHITE};
              border-radius: 50%;
              box-shadow: ${STYLE_CONFIG.MARKER.SHADOW.DEFAULT};
              display: flex;
              align-items: center;
              justify-content: center;
              color: ${STYLE_CONFIG.MARKER.COLORS.WHITE};
              font-size: 16px;
              font-weight: bold;
              cursor: pointer;
              transition: all 0.3s;
            ">${city.stores.length}</div>
          `;

          const marker = new window.AMap.Marker({
            position: city.position,
            content: markerContent,
            title: city.name,
            offset: new window.AMap.Pixel(
              -STYLE_CONFIG.MARKER.SIZE.WIDTH/2, 
              -STYLE_CONFIG.MARKER.SIZE.HEIGHT/2
            ),
            label: {
              content: `<div style="
                padding: 6px 12px;
                background: rgba(255, 255, 255, 0.98);
                border-radius: 4px;
                border: 1px solid ${STYLE_CONFIG.MARKER.COLORS.BORDER};
                color: ${STYLE_CONFIG.MARKER.COLORS.PRIMARY};
                font-size: 14px;
                white-space: nowrap;
                box-shadow: 0 4px 12px rgba(0,0,0,0.08);
                backdrop-filter: blur(4px);
              ">${city.name}</div>`,
              direction: 'top'
            }
          });

          // 鼠标悬停事件
          marker.on('mouseover', () => {
            const content = `<div style="
              padding: 8px 12px;
              background: rgba(255, 255, 255, 0.98);
              border-radius: 4px;
              border: 1px solid ${STYLE_CONFIG.MARKER.COLORS.BORDER};
              box-shadow: 0 4px 12px rgba(0,0,0,0.08);
              backdrop-filter: blur(4px);
              font-size: 14px;
              color: ${STYLE_CONFIG.MARKER.COLORS.TEXT_PRIMARY};
            ">
              <span style="font-weight: bold; color: ${STYLE_CONFIG.MARKER.COLORS.PRIMARY};">${city.name}</span>
              <br/>
              <span style="color: ${STYLE_CONFIG.MARKER.COLORS.TEXT_SECONDARY};">共${city.stores.length}家门店</span>
            </div>`;

            const position = marker.getPosition();
            hoverInfoWindow.setContent(content);
            hoverInfoWindow.open(map, position);

            const markerDiv = marker.getContentDom().querySelector('div');
            if (markerDiv) {
              markerDiv.style.transform = 'scale(1.1)';
              markerDiv.style.background = STYLE_CONFIG.MARKER.COLORS.PRIMARY_ALPHA_HOVER;
              markerDiv.style.boxShadow = STYLE_CONFIG.MARKER.SHADOW.HOVER;
            }
          });

          // 鼠标移出事件
          marker.on('mouseout', () => {
            hoverInfoWindow.close();

            const markerDiv = marker.getContentDom().querySelector('div');
            if (markerDiv) {
              markerDiv.style.transform = 'scale(1)';
              markerDiv.style.background = STYLE_CONFIG.MARKER.COLORS.PRIMARY_ALPHA;
              markerDiv.style.boxShadow = STYLE_CONFIG.MARKER.SHADOW.DEFAULT;
            }
          });

          // 点击事件
          marker.on('click', () => {
            if (storeMarkerRef.current) {
              map.remove(storeMarkerRef.current);
              storeMarkerRef.current = null;
            }

            const content = createInfoWindowContent(city);
            infoWindow.setContent(content);
            infoWindow.open(map, city.position);
            hoverInfoWindow.close();

            map.setZoomAndCenter(12, city.position, true);
          });

          return marker;
        });

        // 将标记添加到地图
        map.add(markers);
        markersRef.current = markers;

        // 设置地图显示范围为中国
        map.setLimitBounds(new window.AMap.Bounds(
          MAP_CONFIG.BOUNDS.SW,
          MAP_CONFIG.BOUNDS.NE
        ));

        setMapReady(true);
      } catch (error) {
        console.error('地图初始化失败:', error);
      }
    };

    initMap();

    return () => {
      mounted = false;
      cleanupMap();
    };
  }, [showStoreLocation, createInfoWindowContent, cleanupMap, optimizeMapCanvases]);

  return (
    <div className="map-container" ref={mapContainer} style={{ width: '100%', height: '100%' }} />
  );
};

export default StoreMapPage;